<?php

/**
 * memberzoneComments actions.
 *
 * @package    jobeet
 * @subpackage memberzoneComments
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class memberzoneAddressesActions extends myFrontendAction
{
  public function executeSubmit(sfWebRequest $request){

	  $messages = array();

	if(($id = $request->getParameter('addressID', false))){
		$this->form = new PublicUserAddressForm(Doctrine::getTable('PublicUserAddresses')->find($id));
	}else{

		$address = new PublicUserAddresses();
		$address->fromArray(
			array(
				'public_user_id' => $this->getUser()->getObject()->getId()
			)
		);

		$this->form = new PublicUserAddressForm($address);
	}
	
	$this->form->bind($request->getParameter($this->form->getName()));

	if($this->form->isValid()){

		$this->form->save();

		$status = 200;
		$shortMessage = 'Success';

	}else{
			$shortMessage = 'Epic fail';
			$status = 500;
			foreach($this->form->getErrorSchema() as $index => $err){
				$messages[$index] = $err . " ";
			}
	}

	return $this->renderPartial('global/json', array(
		'item' => array(
			'messages' => $messages,
			'status' => $status,
			'shortMessage' => $shortMessage
		)
	));

  }

  public function executeGetForm(sfWebRequest $request){
	$this->setLayout(false);
	
	$address = Doctrine::getTable('PublicUserAddresses')->findOneByPublicUserIdAndId(
		$this->getUser()->getObject()->getId(),
		$request->getParameter('address', -1)
	);

	if($address){
		$this->form = new PublicUserAddressForm($address);
			
	}else{
		switch($request->getParameter('address')){
			case 'shipping':
				$address = new PublicUserShippingAddress();
				$address->fromArray(
					array(
						'public_user_id' => $this->getUser()->getObject()->getId(),
						'type' => 'shipping',
					)
				);
				$this->form = new PublicUserAddressForm($address);
				break;
			case 'billing':
				$address = new PublicUserShippingAddress();
				$address->fromArray(
					array(
						'public_user_id' => $this->getUser()->getObject()->getId(),
						'type' => 'billing',
					)
				);
				$this->form = new PublicUserAddressForm($address);
				break;
		}
	}

	$formHTML = $this->getPartial('memberzoneAddresses/form', array('form' => $this->form));


	return $this->renderPartial('global/json', array(
		'item' => array(
			'formHTML' => $formHTML
		)
	));

  }
}
